<template>
  <div :loading="loading" element-loading-text="加载中。。。">
    <el-card style="overflow:visible;">
      <el-form :model="form" size="mini" :rules="rules" label-position="top" ref="form">
        <el-row :gutter="10">
          <el-col :lg="4" :md="6">
            <el-form-item label='班' prop='company'>
              <el-select v-model="form.company" placeholder="请选择班" @change="queryClass">
                <el-option key="index" label="全部" value="">
                </el-option>
                <el-option v-for="item in companyList" :key="item.TEAMID" :label="(item.TEAMID+'-'+item.TEAMNAME)"
                  :value="item.TEAMID">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :lg="4">
              <el-form-item label="组" prop="team">
                <el-select v-model="form.team" filterable placeholder="请选择组" @change="agentQuery">
                  <el-option key="index" label="全部" value="">
                  </el-option>
                  <el-option v-for="item in teamList" :key="item.TEAMID" :label="(item.TEAMID+'-'+item.TEAMNAME)"
                    :value="item.TEAMID"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          <el-col :md="6" :lg="4">
            <el-form-item label="坐席" prop="agentid">
              <el-select v-model="form.agentid" multiple placeholder="请选择坐席">
                <el-option v-for="item in agentOptions" :key="item.AGENTID" :label="(item.AGENTID+'-'+item.AGENTNAME)"
                  :value="item.AGENTID"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :md="6" :lg="4">
            <el-form-item label='开始日期' class='typeInfo-el-form-item' prop='startdate'>
              <el-date-picker v-model="form.startdate" style="width:100%;" value-format="yyyyMMdd" @change="dateChange"
                type="date" placeholder="选择开始日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :md="6" :lg="4">
            <el-form-item label='结束日期' class='typeInfo-el-form-item' prop='enddate'>
              <el-date-picker v-model="form.enddate" style="width:100%;" value-format="yyyyMMdd" @change="dateChange"
                type="date" placeholder="选择结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :lg="2" :md="3" class="searchBtnMarginTop">
            <el-button type="primary" icon="el-icon-search" :loading="loading" @click="query(1)" size="mini">查询
            </el-button>
          </el-col>
          <el-col :md="3" :lg="2" class="searchBtnMarginTop">
            <el-button type="warning" size="mini" icon="el-icon-refresh" @click="clearForm('form')">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <el-card style="margin-top:10px;">
      <el-row :gutter="10">
        <el-col :lg="2" :md="3" v-if="btnPermission('Button_User_Download')">
          <el-button type="primary" size="mini" icon="el-icon-download" :load="this.download"
            :disabled="tableData.length==0" @click="getExcel">导出</el-button>
        </el-col>
      </el-row>
      <el-table :data="tableData" ref="tableData" border class="tableMarginTop" header-row-class-name="tableHeaderClass"
        highlight-current-row @selection-change="handleCurrentChange" style="min-height:390px;">
        <el-table-column type="selection" width="40px"></el-table-column>
        <el-table-column prop="AGENTID" label="坐席工号"></el-table-column>
        <el-table-column prop="OPRDATE" label="操作日期"></el-table-column>
        <el-table-column prop="OPTTIME" label="操作时间"></el-table-column>
        <el-table-column prop="STATUS" label="坐席状态" :formatter="dataFormat"></el-table-column>

      </el-table>
      <div style="text-align:right;margin-top:20px;">
        <el-pagination @size-change="handleSizeChange" :page-sizes="[10,25,50,100]" :page-size="pageSize"
          @current-change="changePage" :current-page="currentPage" layout="total,sizes, prev, pager, next, jumper"
          background :total="totalRcrdNum"></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
  import toolBox from "@/common/utils/toolBox";
  import query from "@/message/siteManagement/agentState/query";
  import request from "@/common/utils/requestYg";
   // 班组接口
  import teamManage from "@/message/seat-manage/setaTeam/teamManage";
  // 坐席维护接口
   import agentManage from "@/message/seat-manage/SeatInfoManage/agentManage";
  // import request1 from "@/common/utils/requestTest";
  import getGlobalParams from "@/common/utils/getGlobalParams";
  // import comQuery from "@/message/siteManagement/agentState/comQuery";
  import agentQuery from "@/message/siteManagement/agentState/agentQuery";
  import getExcel from "@/message/siteManagement/agentState/getExcel";
  export default {
    data() {
      return {
        download: false,
        loading: false,
        tableData: [],
        currentPage: 1,
        currentRow: [],
        totalRcrdNum: 0,
        companyList: [],
        teamList: [],
        agentOptions: [],
        list1: [],
        filename: "",
        fileUrl: getGlobalParams.get("agentDownloadAddress"),
        pageSize: getGlobalParams.get("PageSize"),
        form: {
          company: "",
          team: "",
          agentid: [],
          startdate: "",
          enddate: ""
        },
        rules: {
          startdate: [{
            required: true,
            message: "开始日期不能为空",
            trigger: "blur"
          }],
          enddate: [{
            required: true,
            message: "结束日期不能为空",
            trigger: "blur"
          }],
        },
        "status": {
          "0": "0-签出",
          "1": "1-签入",
          "2": "2-就绪",
          "3": "3-示忙",
          "4": "4-话后处理",
          "5": "5-通话中",
          "6": "6-振铃",
          "7": "7-拨号",
          "40": "40-呼入话后处理",
          "41": "41-外呼话后处理",
          "50": "50-呼入通话中",
          "51": "51-外呼通话中"
        }
      }
    },
    mounted() {
      this.form.startdate = toolBox.getNowTime(0);
      this.form.enddate = toolBox.getNowTime(0);
      this.queryClass()
      this.agentQuery()
      // this.query();
    },
    methods: {
       // 查询坐席
      async agentQuery() {
        let resBody = new agentManage();
        resBody.data.OPERATION = '5'
        resBody.data.AGENTCLASS = this.seatForm.company
        resBody.data.AGENTTEAM = this.seatForm.team
        // resBody.data.PAGEFLAG = '5'
        let response = await requestYg(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
           this.agentOptions = response.RSP_BODY.struct;
        }else {
          this.$message({
            type: "error",
            message: '该组下没有关联的坐席'
          })
          this.seatForm.team = ''
          this.agentOptions = []
        }
      },
      // 查询班
      async queryClass() {
        let resBody = new teamManage();
        resBody.data.OPERATION = "4";
        resBody.data.TEAMTYPE = "1";
        let response = await requestYg(resBody);
        if (response.SYS_HEAD.ReturnCode == "000000") {
           this.companyList = response.RSP_BODY.struct;
        }else {
          this.$message({
            type: "error",
            message: "请求失败，错误码:" + response.SYS_HEAD.ReturnCode + "，错误信息：" + response.SYS_HEAD.ReturnMessage
          })
          this.companyList = []
        }
      },
      // 查询组
      async queryTeam() {
        this.seatForm.team = ''
        if(this.seatForm.company == ''){
          this.seatForm.team = ''
          return
        }
         let resBody = new teamManage();
        resBody.data.OPERATION = '4'
        resBody.data.TEAMTYPE = '2'
        resBody.data.PAGEFLAG = 4
        resBody.data.CURRPAGE = 1
        resBody.data.PAGEROWNUM = 100
        resBody.data.HTEAMID = this.seatForm.company
        let response = await requestYg(resBody);
        if (response.SYS_HEAD.ReturnCode === "000000") {
          this.teamList = response.RSP_BODY.struct
          this.agentQuery()
        } else {
          this.$message({
            type: "error",
            message: '该班下没有对应组'
          });
          this.teamList = []
          this.seatForm.team = ''
          this.seatForm.company =''
        }
      },
      // comQuery() {
      //   //模板配置查询
      //   let resBody = new comQuery();
      //   resBody.data.TEAMTYPE = "1";
      //   request1(resBody)
      //     .then(response => {
      //       if (response.SYS_HEAD.ReturnCode === "000000") {
      //         this.companyList = response.RSP_BODY.RspStruct || [];
      //       } else {
      //         this.$message({
      //           type: "error",
      //           message: response.SYS_HEAD.ReturnMessage
      //         });
      //         this.companyList = [];
      //       }
      //       this.loading = false;
      //     })
      //     .catch(error => {
      //       this.loading = false;
      //     })

      // },
      // //查询坐席
      // agentQuery(val) {
      //   this.agentOptions = [];
      //   this.form.agentid = [];
      //   let resBody = new agentQuery();
      //   resBody.data.agentdep = this.form.company;
      //   resBody.data.agentteam = val;
      //   request(resBody)
      //     .then(response => {
      //       if (response.SYS_HEAD.ReturnCode === "000000") {
      //         this.agentOptions = response.RSP_BODY.agentOptions || [];
      //       } else {
      //         this.$message({
      //           type: "error",
      //           message: response.SYS_HEAD.ReturnMessage
      //         });
      //         this.agentOptions = [];
      //       }
      //       this.loading = false;
      //     })
      //     .catch(error => {
      //       this.loading = false;
      //     })

      // },
      //数据模板ID初始化下拉框
      // queryTeam(val) {
      //   if (val === "") {
      //     this.teamList = [];
      //     this.agentOptions = [];
      //     this.form.agentid = [];
      //     this.form.team = "";
      //   } else {
      //     this.teamList = [];
      //     this.agentOptions = [];
      //     this.form.agentid = [];
      //     this.form.team = "";
      //     let resBody = new comQuery();
      //     resBody.data.TEAMID = '';
      //     resBody.data.TEAMNAME = '';
      //     resBody.data.TEAMLEVEL = '';
      //     resBody.data.TEAMTYPE = '0';
      //     resBody.data.HTEAMID = val;
      //     resBody.data.pageflag = 4;
      //     resBody.data.pagerownum = 999999;
      //     resBody.data.currpage = this.currentPage;
      //     request1(resBody)
      //       .then(response => {
      //         if (response.SYS_HEAD.ReturnCode === "000000") {
      //           this.teamList = response.RSP_BODY.RspStruct || [];
      //           this.agentQuery("");
      //         } else {
      //           this.$message({
      //             type: "error",
      //             message: response.SYS_HEAD.ReturnMessage
      //           });
      //           this.teamList = [];
      //         }
      //       })
      //       .catch(error => {})
      //   }

      // },
      // query(num) {
      //   this.$refs["form"].validate(valid => {
      //     if (valid) {
      //       this.currentPage = num;
      //       this.loading = true;
      //       let resBody = new query();
      //       let list = "";
      //       if (this.form.agentid != null) {
      //         for (let i = 0; i < this.form.agentid.length; i++) {
      //           if (i == 0) {
      //             list = "'" + this.form.agentid[i] + "'";
      //           } else {
      //             list = list + "," + "'" + this.form.agentid[i] + "'";
      //           }
      //         }
      //         // console.log("=============", list);
      //       }
      //       resBody.data.company = this.form.company;
      //       resBody.data.group = this.form.team,
      //         resBody.data.agentid = list;
      //       resBody.data.begindate = this.form.startdate;
      //       resBody.data.enddate = this.form.enddate;
      //       resBody.data.pageflag = 4;
      //       resBody.data.currpage = this.currentPage;
      //       resBody.data.pagerownum = this.pageSize;

      //       request(resBody)
      //         .then(response => {
      //           if (response.SYS_HEAD.ReturnCode === "000000") {
      //             this.tableData = response.RSP_BODY.agentOptions || [];
      //             this.totalRcrdNum = response.RSP_BODY.TotalNum;
      //             console.log("tableData", this.tableData.length);
      //           } else {
      //             this.$message({
      //               type: "error",
      //               message: response.SYS_HEAD.ReturnMessage
      //             });
      //             this.tableData = [];
      //             this.totalRcrdNum = 0;
      //           }
      //           this.loading = false;
      //         })
      //         .catch(error => {
      //           this.loading = false;
      //         })
      //     } else {
      //       this.$message({
      //         type: "warning",
      //         message: "请输入合法的数据！"
      //       });
      //       return false;
      //     }
      //   });
      // },
      downFile() {
        this.download = false;
        if (this.filename.length == 0) {
          this.$message({
            type: "error",
            message: `文件不存在，无法下载`
          });

        } else {
          window.location.href = this.fileUrl + this.filename;
        }
      },
      getExcel() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.$message({
              type: "success",
              message: `正在下载。。。。。。`
            });
            this.download = true;
            let resBody = new getExcel();
            let list = "";
            if (this.form.agentid != null) {
              for (let i = 0; i < this.form.agentid.length; i++) {
                if (i == 0) {
                  list = "'" + this.form.agentid[i] + "'";
                } else {
                  list = list + "," + "'" + this.form.agentid[i] + "'";
                }
              }
              // console.log("=============", list);
            }
            resBody.data.company = this.form.company;
            resBody.data.group = this.form.team,
              resBody.data.agentid = list;
            resBody.data.begindate = this.form.startdate;
            resBody.data.enddate = this.form.enddate;
            resBody.data.code = "Y014";

            request(resBody)
              .then(response => {
                if (response.SYS_HEAD.ReturnCode === "000000") {
                  this.filename = response.RSP_BODY.filepath;
                  console.log("this.filename", this.filename);
                  this.downFile();
                } else {
                  this.$message({
                    type: "error",
                    message: response.SYS_HEAD.ReturnMessage
                  });
                }
                this.loading = false;
              })
              .catch(error => {
                this.loading = false;
              })
          } else {
            this.$message({
              type: "warning",
              message: "请输入合法的数据！"
            });
            return false;
          }
        });
      },
      dataFormat(row, column) {
        if (column.property == "STATUS")
          return this.status[row[column.property]];
      },
      clearForm(item) {
        this.$refs["" + item].resetFields();
        this.form.startdate = toolBox.getNowTime(0);
        this.form.enddate = toolBox.getNowTime(0);
      },
      changePage(val) {
        // console.log("val", val);
        // this.currentPage = val;
        this.query(val);
      },
      handleSizeChange(val) {
        this.pageSize = val;
        this.query(1);
      },
      handleCurrentChange(val) {
        this.currentRow = val;
      },
      dateChange() {
        let date1 = new Date(toolBox.timeFormat2Date(this.form.startdate)) / 1000 / 3600 / 24;
        let date2 = new Date(toolBox.timeFormat2Date(this.form.enddate)) / 1000 / 3600 / 24;
        let sumDate = date2 - date1;
        let currentdate = new Date(toolBox.timeFormat2Date(toolBox.getNowTime(0))) / 1000 / 3600 / 24;
        let day1 = date2 - currentdate;

        if (sumDate < 0) {
          this.$message({
            type: "warning",
            message: "开始日期不能大于结束日期"
          })
          this.form.startdate = this.toolBox.getNowTime(-day1 + 30);
        }
        if (sumDate > 30) {
          this.$message({
            type: "warning",
            message: "开始日期和结束日期的跨度不能大于一个月"
          })
          this.form.startdate = this.toolBox.getNowTime(-day1 + 30);
        }
      }
    }
  }

</script>
